package com.gouwudai.gobbs.dao.impl;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.gouwudai.gobbs.common.IPageList;
import com.gouwudai.gobbs.dao.ITopicDAO;
import com.gouwudai.gobbs.pojo.TbbsTopic;
import com.gouwudai.gobbs.pojo.TbbsTopicContent;
import com.gouwudai.gobbs.pojo.TbbsTopicRe;
import com.litt.core.common.PageParam;
import com.litt.core.common.Utility;
import com.litt.core.exception.DBException;

public class TopicDAOImpl extends BaseDAOImpl implements ITopicDAO 
{
	private static final Logger logger = Logger.getLogger(TopicDAOImpl.class);	
	private static final String BUSI_NAME = "主题信息";
	
	/**
	 * 保存主题：先保存主题、再保存回复、再保存内容,最后更新主题的topicReId
	 * @param tbbsTopic
	 * @param tbbsTopicRe
	 * @param tbbsTopicContent
	 * @return
	 */
	public Integer saveTopic(TbbsTopic tbbsTopic,TbbsTopicRe tbbsTopicRe,TbbsTopicContent tbbsTopicContent)
	{ 	
		Integer topicId = super.saveObject(tbbsTopic);	
		tbbsTopicRe.setTopicId(topicId);
		tbbsTopicContent.setTopicId(topicId);
		Integer topicReId = super.saveObject(tbbsTopicRe);	
		tbbsTopicContent.setTopicReId(topicReId);
		super.saveObject(tbbsTopicContent);
		//更新tbbsTopic中的topicReId
		super.updateObject("update TbbsTopic obj set obj.topicReId=? where obj.topicId=?", new Object[]{topicReId,topicId});
		return topicId;		
	}
	
	/**
	 * 回复主题：先保存回复、再保存内容,最后更新主题的最后回复人
	 * @param tbbsTopic
	 * @param tbbsTopicRe
	 * @param tbbsTopicContent
	 * @return
	 */
	public void doReTopic(TbbsTopic tbbsTopic,TbbsTopicRe tbbsTopicRe,TbbsTopicContent tbbsTopicContent)
	{ 		
		Integer topicReId = super.saveObject(tbbsTopicRe);	
		tbbsTopicContent.setTopicReId(topicReId);
		super.saveObject(tbbsTopicContent);
		//更新tbbsTopic中的最后回复人
		super.updateObject(tbbsTopic);			
	}
	
	/**
	 * 编辑主题
	 * @param tbbsTopic
	 * @param tbbsTopicRe
	 * @param tbbsTopicContent
	 * @throws DBException
	 */
	public void doEditTopic(TbbsTopic tbbsTopic,TbbsTopicRe tbbsTopicRe,TbbsTopicContent tbbsTopicContent)
	{ 		
		if(tbbsTopic!=null)
			super.updateObject(tbbsTopic);
		super.updateObject(tbbsTopicRe);			
		super.updateObject(tbbsTopicContent);					
	}		
	
	public TbbsTopic load(Integer id)
	{
		return (TbbsTopic)super.loadObject(TbbsTopic.class, id);
	} 
	
	/**
	 * 移动帖子
     * 
	 * @param topicId 主题ID
	 * @param moveClassId 目标版面ID
	 * @param moveClassParentId 目标版面父ID
	 * @param moveUser 操作人员
	 * @param saveLink 判断送是否在原来的版面保留链接
	 */
    public void doMoveTopic(Integer topicId ,Integer moveClassId,Integer moveClassParentId,String moveUser,boolean saveLink)
    {
    	StringBuilder hql = new StringBuilder("update TbbsTopic set classId=?,classParentId=?,moveUser=?,moveTime=?");
        if(saveLink)
        	hql.append(", moveClassId=classId");
        else
        	hql.append(", moveClassId=0");    	
        hql.append(" where topicId=?");
        super.updateObject(hql.toString(), new Object[]{
            moveClassId,
            moveClassParentId,
        	moveUser,
        	new Date(),
        	topicId});

    }
    
    /**
     * 主题表的浏览次数累加
     * @param topicId

     */
    public void updateTopicViewCount(Integer topicId)
    {
    	StringBuilder hql = new StringBuilder("update TbbsTopic set topicViewCount=topicViewCount+1 where topicId=?");
        super.updateObject(hql.toString(), new Object[]{topicId});
    } 
    
    /**
     * 主题表的回复次数累加
     * @param topicId
     * @param lastReUser
     * @param lastReTime

     */
    public void updateTopicReCount(Integer topicId,String lastReUser,Date lastReTime)
    {
    	StringBuilder hql = new StringBuilder("update TbbsTopic set topicReCount=topicReCount+1,topicLastReUser=?,topicLastReTime=? where topicId=?");
        super.updateObject(hql.toString(), new Object[]{lastReUser,lastReTime,topicId});
    }
    
    /**
     * 审核主题
     * @param topicId

     */
    public void doCheckTopic(Integer topicId)
    {
    	StringBuilder hql = new StringBuilder("update TbbsTopic set topicIsPass=1 where topicId=?");
        super.updateObject(hql.toString(), new Object[]{topicId});
    }    

    /**
     * 修改主题类型.
     * 
     * @param topicId 主题ID
     * @param topicPro 主题属性
     */
    public void updateTopicPro(Integer topicPro,Integer topicId)
    {
    	StringBuilder hql = new StringBuilder("update TbbsTopic set topicPro=? where topicId=?");
        super.updateObject(hql.toString(), new Object[]{topicPro,topicId});
    } 
    
    /**
     * 修改主题置顶.
     * 
     * @param topicOnTop 主题置顶
     * @param topicId 主题ID
     */
    public void updateTopicOnTop(Integer topicOnTop,Integer topicId)
    {
        StringBuilder hql = new StringBuilder("update TbbsTopic set topicOnTop=? where topicId=?");
        super.updateObject(hql.toString(), new Object[]{topicOnTop,topicId});
    }     
    
    
    /**
     * 逻辑删除多个主题
     * @param topicIds
     */
    public void deleteLogic(String topicIds)
    {
    	StringBuilder hql = new StringBuilder("update TbbsTopic set topicIsDel=1 where topicId in(");
        hql.append(topicIds);
        hql.append(")");
        super.executeHql(hql.toString());
    }
    
    /**
     * 还原已删除多个主题
     * @param topicIds
     */
    public void doResume(String topicIds)
    {
        StringBuilder hql = new StringBuilder("update TbbsTopic set topicIsDel=0 where topicId in(");
        hql.append(topicIds);
        hql.append(")");
        super.executeHql(hql.toString());
    }    
    
    /**
     * 物理删除主题
     * @param topicId

     */
    public void delete(Integer topicId)
    {
        //删除主题
    	super.deleteObject(TbbsTopic.class.getName(),"topicId",topicId);
    	//删除主题回复
    	super.deleteObject(TbbsTopicRe.class.getName(),"topicId",topicId);
    	//删除主题回复
    	super.deleteObject(TbbsTopicContent.class.getName(),"topicId",topicId);
    }
    
/*************************************************************************/    
 
    
    /**
     * 查询当前版面的主题信息.
     * 
     * @param pageParam 分页查询对象
     * 
     * @return
     */
    public List listByClass(PageParam pageParam)
    {
    	Integer classId = pageParam.getIntegerCond("classId");
        String menuStyle = pageParam.getStringCond("menuStyle");
        
        StringBuilder listHql = new StringBuilder("from TbbsTopic where (classId=");
    	listHql.append(classId);  
    	listHql.append(" or classParentId=");
    	listHql.append(classId);
    	listHql.append(") and topicIsPass=1");
        if(!Utility.isEmpty(menuStyle))
        {
            if(menuStyle.equals("CurNew"))  //最新更新，按最后更新时间倒序排序
            {
                listHql.append(" order by topicLastReTime desc");
            }
            else if(menuStyle.equals("CurTopic")) //最新发表，按发表时间倒序排序
            {
                listHql.append(" order by topicOrder desc, topicId desc");
            }
            else if(menuStyle.equals("CurHot")) //热门主题，浏览或回复大于系统指定数量的按回复数倒序排序
            {
                listHql.append(" order by topicOrder desc, topicReCount desc, topicViewCount desc,topicId desc");
            }
            else if(menuStyle.equals("CurBest")) //最新精品，TOPIC_PRO=3按发表时间倒序排序
            {
                listHql.append(" and topicPro=3");
            }
            else if(menuStyle.equals("CurAsk")) //最新提问，TOPIC_TYPE=3并按发表时间倒序排序
            {
                listHql.append(" and topicType=4");
            }
            else if(menuStyle.equals("CurAnswer")) //最新结贴，TOPIC_TYPE=5
            {
                listHql.append(" and topicType=6");
            }
        }

    	return super.listByHql(listHql.toString(),pageParam.getPageIndex(),pageParam.getPageSize());
    }
    
    /**
     * 查询当前版面的主题信息数量（供分页）.
     * 
     * @param pageParam 分页查询对象
     * 
     * @return
     */
    public int listCountByClass(PageParam pageParam)
    {
        Integer classId = pageParam.getIntegerCond("classId");
        String menuStyle = pageParam.getStringCond("menuStyle");
        
        StringBuilder listHql = new StringBuilder("select count(*) from TbbsTopic where (classId=");
    	listHql.append(classId);
    	listHql.append(" or classParentId=");
    	listHql.append(classId);
    	listHql.append(") and topicIsPass=1");
        if(!Utility.isEmpty(menuStyle))
        {
            if(menuStyle.equals("CurNew"))  //最新更新，按最后更新时间倒序排序
            {
                //listHql.append(" order by topicLastReTime desc");
            }
            else if(menuStyle.equals("CurTopic")) //最新发表，按发表时间倒序排序
            {
                //listHql.append(" order by topicOrder desc, topicId desc");
            }
            else if(menuStyle.equals("CurHot")) //热门主题，浏览或回复大于系统指定数量的按回复数倒序排序
            {
                //listHql.append(" order by topicOrder desc, topicReCount desc, topicViewCount desc,topicId desc");
            }
            else if(menuStyle.equals("CurBest")) //最新精品，TOPIC_PRO=3按发表时间倒序排序
            {
                listHql.append(" and topicPro=3");
            }
            else if(menuStyle.equals("CurAsk")) //最新提问，TOPIC_TYPE=3并按发表时间倒序排序
            {
                listHql.append(" and topicType=4");
            }
            else if(menuStyle.equals("CurAnswer")) //最新结贴，TOPIC_TYPE=5
            {
                listHql.append(" and topicType=6");
            }
        }
    	return super.listHqlCount(listHql.toString());
    } 
/*************************************************************************/
    
    /**
     * 根据主题属性查询
     * @param topicPro
     * @param size
     * @return

     */
    public List listByPro(Integer topicPro,int pageSize)
    {
    	StringBuilder listHql = new StringBuilder("from TbbsTopic where topicPro=");
    	listHql.append(topicPro);
    	listHql.append(" and topicIsPass=1");
    	return super.listByHql(listHql.toString(),1,pageSize);
    }   
    
    /**
     * 基本分页查询
     * @param pageParam
     * @return IPageList
     */
    public IPageList listPage(PageParam pageParam)
    {       
    	String listSql = "SELECT A.*,B.DICT_CONTENT AS TOPIC_TYPE_NAME,C.DICT_CONTENT AS TOPIC_PRO_NAME FROM TbbsTopic A,TbbsDictparam B,TbbsDictparam C WHERE (A.TOPIC_TYPE=B.DICT_VALUE AND B.DICT_TYPE='T001') AND (A.TOPIC_PRO=C.DICT_VALUE AND C.DICT_TYPE='T002')";    	
  	
    	return super.listSqlPage(listSql.toString(),pageParam.getPageIndex(),pageParam.getPageSize());
    }
    
    /**
     * 后台文章管理表格查询
     * 查询条件：查询类型(listType):0-全部，1-已认证主题，2-未认证主题，3-回收站主题
     *         主题名称(title)
     *         所在版面(classId)
     *         主题类型(topicType)
     * @return IPageList
     */
    public IPageList listManagePage(PageParam pageParam)
    {    
        StringBuilder listSql = new StringBuilder("SELECT A.*,B.DICT_CONTENT AS TOPIC_TYPE_NAME,C.DICT_CONTENT AS TOPIC_PRO_NAME,D.CLASS_NAME AS CLASS_NAME FROM TbbsTopic A,TbbsDictparam B,TbbsDictparam C,TbbsClass D WHERE (A.TOPIC_TYPE=B.DICT_VALUE AND B.DICT_TYPE='T001') AND (A.TOPIC_PRO=C.DICT_VALUE AND C.DICT_TYPE='T002') AND A.CLASS_ID=D.CLASS_ID ");
        //查询条件：listType
        int listType = Utility.parseInt(pageParam.getStringCond("listType"));         
        switch(listType)
        {
            case 1:
                listSql.append(" AND A.TOPIC_IS_PASS=1");
                break;
            case 2:
                listSql.append(" AND A.TOPIC_IS_PASS=0");
                break;
            case 3:
                listSql.append(" AND A.TOPIC_IS_DEL=1");
                break;
            default:
                break; 
        }
        //查询条件：title
        String title = pageParam.getStringCond("title");
        if(!Utility.isEmpty(title))
        {
            listSql.append(" AND A.TITLE LIKE '%");
            listSql.append(title);
            listSql.append("%'");
        }
        //查询条件：classId
        int classId = Utility.parseInt(pageParam.getIntegerCond("classId"));  
        if(classId>0)
        {
            listSql.append(" AND A.CLASS_ID=");
            listSql.append(classId);            
        }  
        //查询条件：topicType
        int topicType = Utility.parseInt(pageParam.getIntegerCond("topicType"));  
        if(topicType>0)
        {
            listSql.append(" AND A.TOPIC_TYPE=");
            listSql.append(topicType);            
        }
        
        return super.listSqlPage(listSql.toString(),pageParam.getPageIndex(),pageParam.getPageSize());
    }    
    
    /**
     * 回收站查询
     * @param pageParam
     * @return IPageList
     */
    public IPageList listRecycle(PageParam pageParam)
    {       
        StringBuilder listSql = new StringBuilder("SELECT A.*,B.DICT_CONTENT AS TOPIC_TYPE_NAME,C.DICT_CONTENT AS TOPIC_PRO_NAME FROM TbbsTopic A,TbbsDictparam B,TbbsDictparam C WHERE A.TOPIC_IS_DEL=1 AND (A.TOPIC_TYPE=B.DICT_VALUE AND B.DICT_TYPE='T001') AND (A.TOPIC_PRO=C.DICT_VALUE AND C.DICT_TYPE='T002') ");       
        
        return super.listSqlPage(listSql.toString(),pageParam.getPageIndex(),pageParam.getPageSize());
    }    
    
    /**
     * 查询最新的10个主题
     * @return
     */
    public List listTop10()
    {	    	
    	StringBuilder listSql = new StringBuilder("SELECT TOP 10 A.*,B.CLASS_NAME FROM TbbsTopic A,TbbsClass B WHERE A.TOPIC_PRO<>4 AND A.TOPIC_IS_PASS=1 AND A.TOPIC_IS_DEL=0 AND A.CLASS_ID=B.CLASS_ID AND B.HIDDEN_FLAG=0 ORDER BY A.TOPIC_ID DESC");    	
   	
    	List rsList = super.listSqlPage(listSql.toString(),1,10).getRsList();
    	return rsList;
    } 
    
    /**
     * 查询我发表的主题或回复
     * @param userId 用户ID
     * @param type -  0.我的主题,1.我的回复
     * @param pageIndex
     * @param pageSize
     * @return

     */
    public List listMyTopic(int userId,int type,int pageIndex,int pageSize)
    {	    	
    	int fetchSize = pageIndex*pageSize;
    	
    	String listSql = "";    	
       	if(type==1)
       	{
       		listSql = "SELECT TOP "+fetchSize+" A.*,B.CLASS_NAME FROM TbbsTopicRe A,TbbsClass B WHERE A.USER_ID="+userId+" AND A.CLASS_ID=B.CLASS_ID ORDER BY A.TOPIC_ID DESC";
       	}	
       	else
       		listSql = "SELECT TOP "+fetchSize+" A.*,B.CLASS_NAME FROM TbbsTopic A,TbbsClass B WHERE A.USER_ID="+userId+" AND A.CLASS_ID=B.CLASS_ID ORDER BY A.TOPIC_ID DESC";
   	
    	List rsList = super.listSqlPage(listSql,pageIndex,pageSize).getRsList();
    	return rsList;
    }
    
    /**
     * 查询我发表的主题或回复
     * @param userId 用户ID
     * @param type - 0.我的主题,1.我的回复
     * @return
     */
    public int listCountMyTopic(int userId,int type)
    {	    	
    	String listSql = "";    	
       	if(type==1)
       	{
       		listSql = "SELECT COUNT(*) FROM TbbsTopicRe A,TbbsClass B WHERE A.USER_ID="+userId+" AND A.CLASS_ID=B.CLASS_ID";
       	}	
       	else
       		listSql = "SELECT COUNT(*) FROM TbbsTopic A,TbbsClass B WHERE A.USER_ID="+userId+" AND A.CLASS_ID=B.CLASS_ID";
    	int count = super.listSqlCount(listSql);
    	return count;
    }     
    
}
